package team.archai.nexus.boot.tool;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.util.Base64;
import java.util.logging.Logger;

/**
 * @description: des加密解密工具类
 * @author: lishibin
 * @create: 2021-03-13 19:24
 **/
public class DesUtil {


    private static Logger log = Logger.getLogger(DesUtil.class.getName());

    /**
     * 偏移变量，固定占8位字节
     */
    private final static String IV_PARAMETER = "12345678";

    private final static int SECRET_KEY_LENGTH = 8;

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "DES";
    /**
     * 加密/解密算法-工作模式-填充模式
     */
    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
    /**
     * 默认编码
     */
    private static final String CHARSET = "utf-8";


    private static Key generateKey(String password) throws Exception {
        DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }

    /**
    * @program: DesUtil
    * @description: 加密
    * @author: lishibin
    * @create: 19:41
    **/
    public static String encrypt(String password, String data) {
        if (password == null || password.length() < SECRET_KEY_LENGTH) {
            throw new RuntimeException("Secret key length is at least 8.");
        }
        if (data == null) {
            return null;
        }
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));
            return new String(Base64.getEncoder().encode(bytes));

        } catch (Exception e) {
            log.info(e.getMessage());
            return data;
        }
    }

    /**
    * @program: DesUtil
    * @description: 解密
    * @author: lishibin
    * @create: 19:41
    **/
    public static String decrypt(String password, String data) {
        if (password == null || password.length() < SECRET_KEY_LENGTH) {
            throw new RuntimeException("Secret key length is at least 8.");
        }
        if (data == null) {
            return null;
        }
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);
        } catch (Exception e) {
            log.info(e.getMessage());
            return data;
        }
    }

}
